package com.jiadakeji.ppm.api.v1;

import com.jiadakeji.ppm.api.common.JsonResult;
import com.jiadakeji.ppm.common.mapper.JsonMapper;
import com.jiadakeji.ppm.common.utils.*;
import com.jiadakeji.ppm.common.web.BaseController;
import com.jiadakeji.ppm.modules.business.dao.CustomerDao;
import com.jiadakeji.ppm.modules.business.entity.Customer;
import com.jiadakeji.ppm.modules.business.service.CustomerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 消费者Controller
 * @author hhaoyu
 * @version 2018-07-05
 */
@RestController("v1_customer")
@RequestMapping(value = "${apiPath}/v1/customer")
@Api(description = "消费者接口")
public class CustomerController extends BaseController {

    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CustomerService customerService;



    @RequestMapping(value = "/get")
    @ApiOperation(value = "获取消费者",httpMethod = "POST",consumes="application/json",notes="根据id")
    public JsonResult<Customer> get(@RequestBody Customer customer, HttpServletRequest request, HttpServletResponse response){
        JsonResult<Customer> result = new JsonResult<>();
        if(StringUtils.isBlank(customer.getId())){
            result.setCode(-1);
            result.setMessage("id不能为空");
            return result;
        }
        Customer cus = customerService.get(customer.getId());
        if(cus == null){
            result.setCode(-1);
            result.setMessage("不存在此消费者");
            return result;
        }
        result.setData(cus);
        return result;
    }


    @RequestMapping(value = "/getByNumCode")
    @ApiOperation(value = "获取消费者",httpMethod = "POST",consumes="application/json",notes="根据id")
    public JsonResult<Customer> getByNumCode(@RequestBody Customer customer, HttpServletRequest request, HttpServletResponse response){
        JsonResult<Customer> result = new JsonResult<>();
        if(StringUtils.isBlank(customer.getNumCode())){
           return result.setCodeAndMessage(-1,"numCode不能为空");
        }
        Customer cus = customerDao.getByNumCode(customer);
        if(cus == null){
            result.setCode(-1);
            result.setMessage("不存在此消费者");
            return result;
        }
        result.setData(cus);
        return result;
    }

    @RequestMapping(value = "/update")
    @ApiOperation(value = "更新消费者信息",httpMethod = "POST",consumes="application/json",notes="根据id")
    public JsonResult<Customer> update(@RequestBody Customer customer, HttpServletRequest request, HttpServletResponse response){
        JsonResult<Customer> result = new JsonResult<>();
        if(StringUtils.isBlank(customer.getId())){
            return result.setCodeAndMessage(-1,"id不能为空");
        }
        customer.setNumCode(null);
        customer.preUpdate();
        customerDao.update(customer);
        result.setData(customer);
        return result;
    }


    @RequestMapping(value = "/insert")
    @ApiOperation(value = "添加消费者",httpMethod = "POST",consumes="application/json")
    public JsonResult<Map<String,String>> insert(@RequestBody Customer customer, HttpServletRequest request, HttpServletResponse response){
        JsonResult<Map<String,String>> result = new JsonResult<>();


        if(customer.getOpenIdCode() != null && StringUtils.isNotBlank(customer.getOpenIdCode())){
            //微信登录的js_code换取openid和session_key
            Map<String,String> map = WechatUtils.jscode2session(customer.getOpenIdCode());
            customer.setOpenid(map.get("openid"));
            customer.setSessionKey(map.get("session_key"));
        }

        Customer temp = customerDao.getByOpenid(customer);
        if(temp != null){// 如果openid已经存在，则做更新且返回已存在的customer
            temp.setSessionKey(customer.getSessionKey());
            // 过滤微信昵称里面的特殊表情和字符
            if(customer.getNickname() != null){
                temp.setNickname(customer.getNickname().replaceAll("[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]", "*"));
            }
            temp.preUpdate();
            customerDao.update(temp);
            Map<String,String> map = new HashMap<>();
            map.put("id",temp.getId());
            result.setData(map);
            return result;
        }

        if(null == customer.getOpenid()){
            result.setMessage("请传code以便换取openid");
            return result;
        }
        // 过滤微信昵称里面的特殊表情和字符
        if(customer.getNickname() != null){
            customer.setNickname(customer.getNickname().replaceAll("[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]", "*"));
        }
        for (int i=0;i<100;i++) {
            customer.setNumCode(IdGen.generaChar(9));
            Customer c = customerDao.getByNumCode(customer);
            if(null == c){
                break;
            }
        }

        customer.preInsert();
        customerDao.insert(customer);
        Map<String,String> map = new HashMap<>();
        map.put("id",customer.getId());
        result.setData(map);
        return result;
    }

    @RequestMapping(value = "/insertPhone")
    @ApiOperation(value = "插入电话",httpMethod = "POST",consumes="application/json",notes="根据id")
    public JsonResult<Customer> insertPhone( @RequestBody Map<String,String> phoneMap){
        JsonResult<Customer> result = new JsonResult<>();

        if(null == phoneMap.get("encryptedData")
                || null ==phoneMap.get("id")
                || null ==phoneMap.get("iv"))   {
            result.setMessage("信息不完整");
            result.setCode(-1);
            return result;
        }
        Customer customer =  customerDao.get(phoneMap.get("id"));
        if(null == customer && null == customer.getSessionKey()){
            result.setCode(-1);
            result.setMessage("找不到用户或用户没有sessionkey");
            return result;
        }

        String json = "";
        try {
            json =  AesCbcUtil.decrypt(phoneMap.get("encryptedData"),customer.getSessionKey(),phoneMap.get("iv"),"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(StringUtils.isBlank(json)){
            result.setCode(-1);
            result.setMessage("解码失败");
            return result;
        }

        Map<String,String> map = (Map<String, String>) JsonMapper.fromJsonString(json,Map.class);
        String phone = map.get("phoneNumber");
        customer.setMobile(phone);
        customerDao.update(customer);

        return result;
    }



}

